package com.aiju.cash.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.aiju.app.SimpleHttpCallback;
import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.bean.Shop;
import com.aiju.cash.R;
import com.aiju.cash.core.api.ShopManagetApi;
import com.aiju.cash.ui.main.adapter.BindStoreAdapter;
import com.aiju.cash.ui.multiple_shops.activity.IShopManagerUiListener;
import com.aiju.cash.ui.multiple_shops.present.ipresent.IShopManagerPresent;
import com.aiju.cash.ui.multiple_shops.present.presentiml.ShopManagerPresent;
import com.aiju.support.recyclerView.DividerItemDecoration;
import com.aiju.utils.CRequest;
import com.aiju.utils.StringUtil;
import com.aiju.utils.T;
import com.aiju.widgit.dialog.DialogHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author: 流冥
 * @Description: 绑定店铺
 */
public class BindStoreActivity extends BaseTitleActivity implements IShopManagerUiListener, BindStoreAdapter.OnClickListener {


    List<Shop> list = new ArrayList<>();
    BindStoreAdapter adapter;
    private RecyclerView recyclerviewTeams;
    private String rId;
    private String pStoreId;//总店铺id
    private String[] storeArrays;
    IShopManagerPresent iShopManagerPresent;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_store);
        initView();
        iShopManagerPresent = new ShopManagerPresent(this, null);

        String shopTypeString = mUser.getShop().getShopTypeString();
        String role = mUser.getRole();
        if (role.equals("0")) {
            //   若是总店长扫描的二维码，则此列表仅展示总店和直营店
            rquestShopList();
        } else if ("加盟店".equals(shopTypeString) || role.equals("1")) {
            //   若是加盟店店长扫描的二维码，列表仅展示加盟店一家店铺
            list.add(mUser.getShop());
            List<Shop> shops = filterList(list);
            adapter = new BindStoreAdapter(shops, mUser);
            recyclerviewTeams.setAdapter(adapter);
        }


    }

    void initView() {
        initTitle();
        initOther();
        initPresent();
        Intent intent = getIntent();
        if (intent != null) {
            String url = intent.getStringExtra("url");
            Map<String, String> stringStringMap = CRequest.URLRequest(url);
            rId = stringStringMap.get("rid");
            pStoreId = stringStringMap.get("pstoreid");
            String storeIdList = stringStringMap.get("storeidlist");
            storeArrays = storeIdList.split(",");
        }

    }

    DialogHelper dialogHelper;

    /**
     * 初始化title
     */
    void initTitle() {
        dialogHelper = new DialogHelper(BindStoreActivity.this);
        setCenterTitle("绑定店铺");
        findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (StringUtil.isBlank(adapter.getStoreIds())) {
                    T.ToastShort("请选择店铺");
                    return;
                }
                dialogHelper.showLoadingProgressDialog();
                // TODO: 2017/7/19 加盟店也上传总店铺id吗 ？、、？
                new ShopManagetApi(null).getGrant(rId, mUser.getParentStoreId(), adapter.getStoreIds(), new SimpleHttpCallback() {
                    @Override
                    protected void onDataSuccess(String data) {
                        mDialogHelper = null;
                        if (200 == jsonData.getCode()) {

                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        Thread.sleep(3100);
                                        getGrantStatus();
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }).start();

                        } else {
                            dialogHelper.dismissProgressDialog();
                            Intent intent = new Intent(BindStoreActivity.this, BindFialActivity.class);
                            startActivity(intent);
                        }
                    }

                    @Override
                    public void onFailure(int code, String errorMessage) {
                        super.onFailure(code, errorMessage);
                        mDialogHelper = null;
                        dialogHelper.dismissProgressDialog();
                    }
                });
            }
        });

    }

    void initOther() {
        recyclerviewTeams = (RecyclerView) findViewById(R.id.recyclerview_member);
        recyclerviewTeams.setLayoutManager(new LinearLayoutManager(this));
        recyclerviewTeams.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));


    }

    void initPresent() {
        iShopManagerPresent = new ShopManagerPresent(this, mDialogHelper);
    }


    /**
     * 请求数据
     */
    private void rquestShopList() {
        iShopManagerPresent.getShopList(0, 0);
    }


    @Override
    public void onManageShop(Shop shopManager) {
        //   跳转到店铺详情
    }


    @Override
    public void NoDate() {//店铺不会无数据，不用考虑
        if (list.size() != 0) {
            //显示无数据界面,不会无数据
        } else {
            //结束刷新状态
            // completeRefrsh();
        }
    }

    @Override
    public void getShopList(List<Shop> mList) {
        List<Shop> shops = filterList(mList);
        if (adapter == null) {
            adapter = new BindStoreAdapter(shops, mUser);
            recyclerviewTeams.setAdapter(adapter);
            adapter.setListener(this);
        } else {
            list.addAll(mList);
            adapter.notifyDataSetChanged();
        }

    }

    @Override
    public void exception() {
    }

    //加入对erp授权的tag
    List<Shop> filterList(List<Shop> list) {
        List<Shop> tempList = new ArrayList<>();
        //只有总店和直营店
        for (int i = 0; i < list.size(); i++) {
            if (!list.get(i).getShopType().equals("2")) {
                tempList.add(list.get(i));
            }
        }
        for (int i = 0; i < storeArrays.length; i++) {
            for (int j = 0; j < tempList.size(); j++) {
                if (storeArrays[i].equals(tempList.get(j).getStoreId())) {
                    tempList.get(j).setERPGranted(true);
                    break;
                }
            }
        }
        return tempList;
    }


    void getGrantStatus() {
        new ShopManagetApi(null).getGrantStatus(rId, new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {
                mDialogHelper = null;
                dialogHelper.dismissProgressDialog();
                if (200 == jsonData.getCode()) {
                    Intent intent = new Intent(BindStoreActivity.this, BindSuccessActivity.class);
                    intent.putExtra("names", adapter.getStoreNames());
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(BindStoreActivity.this, BindFialActivity.class);
                    startActivity(intent);
                }
            }


            @Override
            protected void onDataFailure(int code, String msg) {
                super.onDataFailure(code, msg);
                mDialogHelper = null;
                dialogHelper.dismissProgressDialog();
                Intent intent = new Intent(BindStoreActivity.this, BindFialActivity.class);
                startActivity(intent);
            }
        });
    }


}
